package com.nineclock.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser query(String username) {
        //校验
        if(StrUtil.isEmpty(username)){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //组装查询条件
        //select * from sys_user where username = '小明' or mobile = 'xxxxxxx'
        LambdaQueryWrapper<SysUser> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(SysUser::getUsername, username).or().eq(SysUser::getMobile, username);

        //执行查询
        SysUser user = sysUserMapper.selectOne(userWrapper);
        return user;
    }


    @Override
    public Boolean checkExists(String mobile) {
        LambdaQueryWrapper<SysUser> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(SysUser::getMobile, mobile); // where mobile = ?

        Integer count = sysUserMapper.selectCount(userWrapper);
        return count == 1;
    }

    @Autowired
    private SmsService smsService;

    @Override
    public Long register(SysRegisterDTO registerDTO) {
        //校验参数
        if(registerDTO == null || StrUtil.isEmpty(registerDTO.getCheckcode()) || StrUtil.isEmpty(registerDTO.getMobile()) || StrUtil.isEmpty(registerDTO.getPassword())){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //手机号无需再次判定, 因为如果手机号已经被注册, 则无法正常获取验证码

        //校验验证码
        Boolean verify = smsService.verify(registerDTO.getCheckcode(), registerDTO.getMobile(), SMSConstant.SMS_TYPE_REGISTER);
        if(!verify){
            throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
        }

        //保存用户数据
        SysUser sysUser = new SysUser();
        sysUser.setMobile(registerDTO.getMobile());
        sysUser.setPassword(new BCryptPasswordEncoder().encode(registerDTO.getPassword()));

        sysUserMapper.insert(sysUser);
        return sysUser.getId(); //插入数据之后, MybatisPlus会自动的将主键返回并赋值给实体类的ID
    }

}
